package com.zytool.easyrestful.core.condition;

import cn.hutool.core.util.StrUtil;
import com.zytool.easyrestful.core.annotation.Condition;
import com.zytool.easyrestful.core.convert.ConvertorHolder;
import com.zytool.easyrestful.core.utils.EntityUtil;
import tk.mybatis.mapper.entity.Example;

import javax.persistence.Column;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

public class EntityExampleBuilder {

    public static Example build(Class entityClazz, Map<String, String> params) {
        List<Field> fieldList = EntityUtil.getFields(entityClazz);
        Example example = new Example(entityClazz);
        Example.Criteria criteria = example.createCriteria();

        for (Field field : fieldList) {
            String fieldName = ConvertorHolder.instance().getConvertor().field2Column(field);
            Column column = field.getAnnotation(Column.class);
            if (column != null) {
                fieldName = column.name();
            }
            String fieldValue = params.get(fieldName);
            Condition condition = field.getAnnotation(Condition.class);
            if (condition != null && (!StrUtil.isBlank(fieldValue) || condition.match() == Match.RANGE)) {
                if (condition.match() == Match.EQ) {
                    criteria.andEqualTo(fieldName, fieldValue);
                } else if (condition.match() == Match.GT) {
                    criteria.andGreaterThan(fieldName, fieldValue);
                } else if (condition.match() == Match.LT) {
                    criteria.andLessThan(fieldName, fieldValue);
                } else if (condition.match() == Match.GTEQ) {
                    criteria.andGreaterThanOrEqualTo(fieldName, fieldValue);
                } else if (condition.match() == Match.LTEQ) {
                    criteria.andGreaterThanOrEqualTo(fieldName, fieldValue);
                } else if (condition.match() == Match.LIKE) {
                    criteria.andLike(fieldName, " %" + fieldValue + "%");
                } else if (condition.match() == Match.LLIKE) {
                    criteria.andLike(fieldName, " %" + fieldValue);
                } else if (condition.match() == Match.RLIKE) {
                    criteria.andLike(fieldName, fieldValue + "%");
                } else if (condition.match() == Match.RANGE) {
                    criteria.andBetween(fieldName, params.get(condition.param1()), params.get(condition.param2()));
                }
            }
        }
        return example;
    }
}
